/*
 * pantallaCita.java
 *
 * Created on 01-may-2011, 20:18:38
 */

package interfaces;

import Controlador.Controlador;
import GestorCitas.*;
import GestorClinico.*;
import GestorPruebas.*;
import GestorUsuarios.*;
import GestorFarmacia.*;

import paciente.*;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import paciente.Interfaz.*;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.jdesktop.application.Action;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author José Ángel Caravajal Soto
 */
public class historialPaciente extends javax.swing.JPanel {

   public class MyRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                     boolean isSelected, boolean hasFocus,
                                                     int row, int column) {
            ImageIcon icon = null;
            if(value.equals("Si")) {
                icon = new ImageIcon(getClass().getResource("/interfaces/resources/Box-green-32.png"));
            } else if(value.equals("No"))
                icon = new ImageIcon(getClass().getResource("/interfaces/resources/Box-red-32.png"));

            setIcon(icon);
            setHorizontalAlignment(CENTER);
            return this;
      }
    }


    /** Creates new form SeleccionarListado */
    private PacienteView app;
    private Cita _cita = null;
    private Paciente _paciente = null;
    private Interfaces _anterior = null;
    ArrayList<LineaReceta> _l_linea_receta = new ArrayList<LineaReceta>();
    Cita _citasAnteriores[] = null;
    ArrayList<Prueba> _l_prueba = new ArrayList<Prueba>();
    int row_modify = -1;

    /** Creates new form buscarCita */
    public historialPaciente (PacienteView a){
        app = a;
        initComponents();

        //tabla citas
        String[] columnNames = {"Médico","Fecha","Recetas","Pruebas"};
        modelo = new DefaultTableModel(null, columnNames);
        linea_cita.setModel(modelo);
        linea_cita.getColumn("Recetas").setCellRenderer(new MyRenderer());
        linea_cita.setRowHeight(32);
        linea_cita.getColumn("Recetas").setWidth(55);
        linea_cita.getColumn("Recetas").setMinWidth(55);
        linea_cita.getColumn("Recetas").setMaxWidth(55);

        linea_cita.getColumn("Pruebas").setCellRenderer(new MyRenderer());
        linea_cita.getColumn("Pruebas").setWidth(55);
        linea_cita.getColumn("Pruebas").setMinWidth(55);
        linea_cita.getColumn("Pruebas").setMaxWidth(55);

        linea_cita.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        //Cargamos eventos para cambio de tab
     


    }

    

        public void rellenaDatos() {

        //Interfaz.limpiarTabla(linea_cita);
        //observacionesPaciente.setText("");


        //Rellenamos los datos del historial de citas
    try{
        _citasAnteriores = Cita.get(Controlador.getUsuarioActivo().getIdUsuario(), null, null, null, null, EstadoCita.FINALIZADA);
        if (_citasAnteriores != null ) {
            rellenaDatosCitas();
        }
        }catch(Exception e){
        }


    }



    public void rellenaDatosCitas() throws SQLException, IOException, ClassNotFoundException, NoSuchAlgorithmException, IDException, ParseException {
        
        DateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[] columnNames = {"Médico","Fecha","Recetas","Pruebas"};
        Object[][] data = new Object[_citasAnteriores.length][];
        for(int i=0;i<_citasAnteriores.length;i++) {
            //try {
                    Usuario m = Usuario.get(_citasAnteriores[i].getIdMedico());
                    Prueba[] p = Prueba.get(_citasAnteriores[i].getIdCita(), null, null, null, null, null, null, null);
                    Receta[] r = Receta.get(null, null, _citasAnteriores[i].getIdCita());
                    String pruebas = "No";
                    String recetas = "No";

                    int cont = 0;
                    if(p!=null)
                    for (Prueba pr : p ) {
                        if ( pr.getEstadoPrueba() == EstadoPrueba.Pendiente || pr.getEstadoPrueba() == EstadoPrueba.Realizada ||
                                pr.getEstadoPrueba() == EstadoPrueba.Visualizable)
                            cont++;
                    }
                    
                    if (r != null) {
                        recetas = "Si";
                    }

                    if ( cont > 0 ) {
                        pruebas = "Si";
                    }
                    
                    data[i] = new Object[4];
                    data[i][0] = m.getNombre() + " " + m.getApellidos() ;
                    data[i][1] = formatoFecha.format(_citasAnteriores[i].getFechaCita());
                    data[i][2] = recetas;
                    data[i][3] = pruebas;
            
            //} catch (IDException ex) {}
            
        }

        modelo = new DefaultTableModel(data, columnNames) {
            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }
        };

        linea_cita.setModel(modelo);
        linea_cita.getColumn("Recetas").setCellRenderer(new MyRenderer());
        linea_cita.setRowHeight(48);
        linea_cita.getColumn("Recetas").setWidth(55);
        linea_cita.getColumn("Recetas").setMinWidth(55);
        linea_cita.getColumn("Recetas").setMaxWidth(55);

        linea_cita.getColumn("Pruebas").setCellRenderer(new MyRenderer());
        linea_cita.getColumn("Pruebas").setWidth(48);
        linea_cita.getColumn("Pruebas").setMinWidth(55);
        linea_cita.getColumn("Pruebas").setMaxWidth(55);
    }

    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel11 = new javax.swing.JLabel();
        jScrollPane8 = new javax.swing.JScrollPane();
        observacionesPaciente = new javax.swing.JTextPane();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane7 = new javax.swing.JScrollPane();
        linea_cita = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        btncitaDetallada = new javax.swing.JButton();

        setMinimumSize(new java.awt.Dimension(640, 480));
        setPreferredSize(new java.awt.Dimension(780, 470));

        jLabel11.setFont(Interfaz.setFontSize());
        jLabel11.setText("Observaciones clínicas"); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        jScrollPane8.setName("jScrollPane8"); // NOI18N

        observacionesPaciente.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        observacionesPaciente.setEnabled(false);
        observacionesPaciente.setName("observacionesPaciente"); // NOI18N
        jScrollPane8.setViewportView(observacionesPaciente);

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Citas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize()));
        jPanel7.setName("jPanel7"); // NOI18N

        jScrollPane7.setName("jScrollPane7"); // NOI18N

        linea_cita.setFont(new java.awt.Font("Tahoma", 0, 18));
        linea_cita.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Médico", "Fecha", "Recetas", "Pruebas"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        linea_cita.setName("linea_cita"); // NOI18N
        linea_cita.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                linea_citaMouseClicked(evt);
            }
        });
        linea_cita.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                linea_citaFocusGained(evt);
            }
        });
        jScrollPane7.setViewportView(linea_cita);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(paciente.PacienteApp.class).getContext().getActionMap(historialPaciente.class, this);
        jButton1.setAction(actionMap.get("aceptar")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(paciente.PacienteApp.class).getContext().getResourceMap(historialPaciente.class);
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setToolTipText("");
        jButton1.setLabel(resourceMap.getString("jButton1.label")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        btncitaDetallada.setAction(actionMap.get("citaDetallada")); // NOI18N
        btncitaDetallada.setIcon(resourceMap.getIcon("jButton5.icon")); // NOI18N
        btncitaDetallada.setName("btncitaDetallada"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel11))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(btncitaDetallada, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 531, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 760, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                .addGap(63, 63, 63)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btncitaDetallada, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleName("contenedor");
    }// </editor-fold>//GEN-END:initComponents

    private void linea_citaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_linea_citaFocusGained
        // TODO add your handling code here:

    }//GEN-LAST:event_linea_citaFocusGained

    private void linea_citaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_linea_citaMouseClicked
        // TODO add your handling code here:
        
        observacionesPaciente.setText(_citasAnteriores[linea_cita.getSelectedRow()].getObservaciones());
    }//GEN-LAST:event_linea_citaMouseClicked

    @Action
    public void aceptar() {
        app.volver(Interfaces.PRINCIPAL_PACIENTE);
    }

    @Action
    public void citaDetallada() throws SQLException, IOException, ClassNotFoundException, NoSuchAlgorithmException, ParseException, IDException {
        int row = linea_cita.getSelectedRow();
        if ( row >= 0 ) {
           app.abrirHistorialPacienteDetallado(_citasAnteriores[row], Interfaces.HISTORIAL_PACIENTE);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btncitaDetallada;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JScrollPane jScrollPane8;
    private javax.swing.JTable linea_cita;
    private javax.swing.JTextPane observacionesPaciente;
    // End of variables declaration//GEN-END:variables

    private TableModel modelo;

}
